<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>我的订单</p>
    </header>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <p>加载订单失败，请重试</p>
      <button @click="reloadOrders">重新加载</button>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="(orderArr || []).length === 0" class="empty">
      <img src="https://picsum.photos/200/200?random=1" alt="暂无订单" />
      <p>暂无订单</p>
    </div>
    
    <!-- 订单列表部分 -->
    <div v-else>
      <h3>未支付订单信息：</h3>
      <ul class="order">
        <li v-for="item in filterOrders(0)" :key="item.id || item.orderId">
          <div class="order-info">
            <p>
              {{getBusinessName(item)}}
              <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
            </p>
            <div class="order-info-right">
              <p>¥{{item.orderTotal || 0}}</p>
              <div class="order-info-right-icon" @click="goPay(item)">去支付</div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.isShowDetailet">
            <li v-for="odItem in item.list || []" :key="odItem.id || odItem.foodId">
              <p>{{getFoodName(odItem)}} x {{odItem.quantity || 0}}</p>
              <p>¥{{getFoodTotalPrice(odItem)}}</p>
            </li>
            <li>
              <p>配送费</p>
              <p>¥{{item.business?.deliveryPrice || 0}}</p>
            </li>
          </ul>
        </li>
      </ul>

      <h3>已支付订单信息：</h3>
      <ul class="order">
        <li v-for="item in filterOrders(1)" :key="item.id || item.orderId">
          <div class="order-info">
            <p>
              {{getBusinessName(item)}}
              <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
            </p>
            <div class="order-info-right">
              <p>¥{{item.orderTotal || 0}}</p>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.isShowDetailet">
            <li v-for="odItem in item.list || []" :key="odItem.id || odItem.foodId">
              <p>{{getFoodName(odItem)}} x {{odItem.quantity || 0}}</p>
              <p>¥{{getFoodTotalPrice(odItem)}}</p>
            </li>
            <li>
              <p>配送费</p>
              <p>¥{{item.business?.deliveryPrice || 0}}</p>
            </li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 底部菜单部分 -->
    <Footer v-if="!loading" />
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'OrderList',
  data() {
    return {
      orderArr: [],
      user: {},
      loading: true,
      error: false
    }
  },
  created() {
    this.loadOrders();
  },
  methods: {
    loadOrders() {
      this.loading = true;
      this.error = false;
      
      this.user = this.$getSessionStorage('user') || {};
      if (!this.user.userId) {
        console.error('用户ID不存在');
        this.loading = false;
        this.error = true;
        return;
      }
      
      this.$axios.post('OrdersController/listOrdersByUserId', this.$qs.stringify({
        userId: this.user.userId
      }))
      .then(response => {
        const result = response.data || [];
        console.log('订单数据:', result);
        
        // 处理订单数据，确保结构完整
        this.orderArr = result.map(item => ({
          ...item,
          isShowDetailet: item.isShowDetailet !== undefined ? item.isShowDetailet : false,
          orderstate: item.orderstate !== undefined ? item.orderstate : 0,
          business: item.business || {},
          list: item.list || []
        }));
        
        this.loading = false;
      })
      .catch(error => {
        console.error('获取订单列表失败:', error);
        this.loading = false;
        this.error = true;
        this.$toast('获取订单列表失败，请稍后再试');
      });
    },
    
    reloadOrders() {
      this.loadOrders();
    },
    
    detailetShow(orders) {
      orders.isShowDetailet = !orders.isShowDetailet;
    },
    
    goPay(item) {
      console.log('去支付:', item);
      // this.$router.push({ name: 'Pay', params: { orderId: item.id } });
    },
    
    filterOrders(state) {
      return (this.orderArr || []).filter(item => {
        // 确保item和orderstate存在
        return item && item.orderstate !== undefined && item.orderstate === state;
      });
    },
    
    getBusinessName(item) {
      return item.business?.businessName || '未知商家';
    },
    
    getFoodName(odItem) {
      return odItem.food?.foodName || '未知商品';
    },
    
    getFoodTotalPrice(odItem) {
      return (odItem.food?.foodPrice || 0) * (odItem.quantity || 0);
    }
  },
  components: {
    Footer
  }
}
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 加载状态 ******************/
.loading {
  padding-top: 40vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 4vw;
}

.spinner {
  width: 12vw;
  height: 12vw;
  border: 2px solid #0097FF;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
  margin-bottom: 4vw;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/****************** 错误状态 ******************/
.error {
  padding-top: 40vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 4vw;
}

.error button {
  margin-top: 4vw;
  padding: 2vw 6vw;
  background-color: #0097FF;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 4vw;
}

/****************** 空状态 ******************/
.empty {
  padding-top: 40vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 4vw;
}

.empty img {
  width: 30vw;
  height: 30vw;
  margin-bottom: 4vw;
  border-radius: 50%;
  opacity: 0.6;
}

/****************** 历史订单列表部分 ******************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order {
  width: 100%;
  padding: 0 3vw;
  box-sizing: border-box;
}

.wrapper .order li {
  width: 100%;
  background-color: #fff;
  margin-bottom: 3vw;
  border-radius: 3px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.wrapper .order li .order-info {
  box-sizing: border-box;
  padding: 3vw 4vw;
  font-size: 4vw;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.wrapper .order li .order-info .order-info-right {
  display: flex;
  align-items: center;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon {
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  margin-left: 2vw;
  user-select: none;
  cursor: pointer;
  padding: 1.5vw 4vw;
  font-size: 3.5vw;
}

.wrapper .order li .order-detailet {
  width: 100%;
  background-color: #f8f8f8;
}

.wrapper .order li .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 2vw 4vw;
  color: #666;
  font-size: 3.5vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  box-shadow: none;
  border-radius: 0;
}

/****************** 底部菜单部分 ******************/
.wrapper Footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}
</style>